#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main( void )
{
	int lisfd, confd, maxfd;
	int fds[1024];
	struct sockaddr_in seraddr, cliaddr;
	fd_set readfds;
	char buf[1480];
	struct timeval t;
	int len , idx, ret, count;

	lisfd = socket( AF_INET, SOCK_STREAM, 0 );
	if ( lisfd < 0 ) {
		printf( "Create socket faild.\n" );
		return -1;
	}

	seraddr.sin_addr.s_addr = INADDR_ANY;
	seraddr.sin_port = htons(1234);
	seraddr.sin_family = AF_INET;

	ret = bind( lisfd, ( struct sockaddr * )&seraddr, sizeof( struct sockaddr ) );
	if ( ret < 0 ) {
		printf( "Bind socket fd failed.\n" );
		close( lisfd );
		return -1;
	}

	listen( lisfd, 1024 );

	maxfd = lisfd;

	memset( &fds, 0, 1024 );
	t.tv_sec = 2;
	while ( 1 ) {
		FD_ZERO( &readfds );
		FD_SET( lisfd, &readfds );

		for ( idx = 0; idx < 1024; idx++ ) {
			if ( fds[idx] != 0 ) {
				FD_SET( fds[idx], &readfds );
			} else
				break;
		}

		t.tv_sec = 2;
		ret = select( maxfd + 1, &readfds, NULL, NULL, &t );
		if ( ret < 0 ) {
			printf( "Select error.\n" );
			return -1;
		} else if ( ret == 0 ) {
			printf( "Time out.\n" );
			continue;
		}

printf( "dfdfdf\n" );
		for ( idx = 0; idx < count; idx++ ) {
			if ( FD_ISSET( fds[idx], &readfds ) ) {
				ret = recv( fds[idx], buf, 1048, 0 );
				if ( ret < 0 ) {
					printf( "Recv failed.\n" );
					close( fds[idx] );
					FD_CLR( fds[idx], &readfds );
					fds[idx] = 0;
				} else {
					send( fds[idx], "disconnect", 10, 0 );
				}
			}
		}

		if ( FD_ISSET( lisfd, &readfds ) ) {
			len = sizeof( struct sockaddr );
			confd = accept( lisfd, ( struct sockaddr * )&cliaddr, &len );
			if ( confd < 0 ) {
				printf( "Accept failed.\n" );
				continue;
			}

			if ( count < 1024 )
				fds[count++] = confd;

			if ( confd > maxfd )
				maxfd = confd;
		}
		
	}

	for ( idx = 0; idx < 1024; idx++ ) {
		if ( fds[idx] !=0 )
			close( fds[idx] );
	}

	return 0;
}


